package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**

 * 体检预约服务

 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpll implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private CheckSetmealDao checkSetmealDao;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;
    @Autowired
    private AddressDao addressDao;

    //添加预约信息
    @Override
    public Result add(OderIofo oderIofo, Integer[] setmealIds) throws Exception {
        //手机号
        String phoneNumber = oderIofo.getPhoneNumber();
        //姓名
        String name = oderIofo.getName();
        //预约日期
        String orderDate = oderIofo.getOrderDate();

        Date date = DateUtils.parseString2Date(orderDate);

        //判断是否能预约
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //预约已满，不能预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //检查当前用户是否为会员，根据手机号判断
        Member member = memberDao.findByTelephone(phoneNumber);

        //防止重复预约
        if(member != null){
            Integer memberId = member.getId();
            for (Integer setmealId : setmealIds) {
                Order order = new Order(memberId,date,null,null,setmealId);
                List<Order> list = orderDao.findByCondition(order);
                if(list != null && list.size() > 0){
                    //已经完成了预约，不能重复预约
                    return new Result(false, MessageConstant.HAS_ORDERED);
                }

            }

        }

        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);


        if(member == null){
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setName(name);
            member.setPhoneNumber(phoneNumber);
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //保存预约信息到预约表

        for (Integer setmealId : setmealIds) {
            Order order = new Order(member.getId(), date, Order.ORDERTYPE_TELEPHONE,

                Order.ORDERSTATUS_NO,

                setmealId);

            orderDao.add(order);
        }


        return new Result(true, MessageConstant.ADD_ORDER_SUCCESS);

    }


    @Override
    public void deleteOrder(Integer id) {
        orderDao.deleteOrder(id);
    }


    @Override
    public OderIofo findBy(Integer id) {
        OderIofo oderIofo=orderDao.findBy(id);
        String name=orderDao.findByIdName(id);
        oderIofo.setName(name);
        return oderIofo;
    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        String queryString = queryPageBean.getQueryString();
        String[] date = queryPageBean.getDate();
        String option1 = queryPageBean.getOption1();
        String option2 = queryPageBean.getOption2();

        Map<String,Object> map = new HashMap<>();
        map.put("queryString",queryString);
        map.put("date",date);
        map.put("option1",option1);
        map.put("option2",option2);
        Page<OderIofo> page = orderDao.selectByCondition(map);

        List<OderIofo> result = page.getResult();
        long total = page.getTotal();
        return  new PageResult(total,result);
    }


//    public List<Map<String,Object>> findByMemberIds(Integer[] memberIds) {
//        List<Map<String, Object>> list = new ArrayList<>();
//        if(memberIds != null &&memberIds.length >0) {
//            for (Integer memberId : memberIds) {
//                Map<String, Object> map = new HashMap<>();
//                Member member = memberDao.findById(memberId);
//                map.put("name", member.getName());
//                map.put("sex", Integer.parseInt(member.getSex()) == 1 ? "男" : "女");
//                map.put("phoneNumber", member.getPhoneNumber());
//                Order order = orderDao.findByMemberId(memberId);
//                //机构地址(不知道是什么)
//                map.put("address", "机构地址");
//                Integer setmealId = order.getSetmealId();
//                Setmeal setmeal = checkSetmealDao.findById(setmealId);
//                map.put("setmealName", setmeal.getName());
//                List<CheckGroup> checkGroups = checkGroupDao.findBySetmealId(setmealId);
//                List allCheckItemName = new ArrayList();
//                List checkgroupName = new ArrayList();
//                for (CheckGroup checkGroup : checkGroups) {
//                    checkgroupName.add(checkGroup.getName());
//                    String[] checkItemName = checkItemDao.findNameByCheckGroupId(checkGroup.getId());
//                    allCheckItemName.add(checkItemName);
//                }
//                map.put("checkgroupName", checkgroupName);
//                map.put("allCheckItemName", allCheckItemName);
//                list.add(map);
//            }
//        }
//        return list;
//    }


    @Override
    public List<Map<String, Object>> findAllMember() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Member> members = memberDao.findAll();
        for (Member member : members) {
            Map<String, Object> map = new HashMap<>();
            if(member != null){
                    map.put("name", member.getName());
                Integer sex = Integer.parseInt(member.getSex());
                    map.put("sex",sex == 1  ? "男" : "女");
                map.put("phoneNumber", member.getPhoneNumber());
                Integer memberId = member.getId();
                Integer setmealId= orderDao.findByMemberId(memberId);
                //机构地址(不知道是什么)
               map.put("address", "机构地址");
                if (memberId != null && setmealId != null) {
                    Setmeal setmeal = checkSetmealDao.findById(setmealId);
                    map.put("setmealName", setmeal.getName());
                    List<CheckGroup> checkGroups = checkGroupDao.findBySetmealId(setmealId);
                    List allCheckItemName = new ArrayList();
                    List checkgroupName = new ArrayList();
                    for (CheckGroup checkGroup : checkGroups) {
                        checkgroupName.add(checkGroup.getName());
                        List<String> checkItemNames = checkItemDao.findNameByCheckGroupId(checkGroup.getId());
                        for (String checkItemName : checkItemNames) {
                            allCheckItemName.add(checkItemName);
                        }
                    }
                    map.put("checkgroupName", checkgroupName);
                    map.put("allCheckItemName", allCheckItemName);
                    list.add(map);
                }
            }
        }
        return list;
    }

    @Override
    public Map findByName(String name) throws Exception {
        Map<String,Object> order = new HashMap<>();
        order.put("name",name);
        Integer memberId = memberDao.findByName(name);
        Order o = orderDao.findOrderByMemberId(memberId);
        order.put("orderDate",DateUtils.parseDate2String(o.getOrderDate()));
        order.put("orderType",o.getOrderType());
        order.put("orderStatus",o.getOrderStatus());
        String address = addressDao.findByOrderId(o.getId());
        order.put("address",address);
        return order;
    }

    @Override
    public Map findByMemberId(Integer memberId) throws Exception {
        Map<String,Object> order = new HashMap<>();
        String name = memberDao.findNameById(memberId);
        order.put("name",name);
        Order o = orderDao.findOrderByMemberId(memberId);
        order.put("orderDate",DateUtils.parseDate2String(o.getOrderDate()));
        order.put("orderType",o.getOrderType());
        order.put("orderStatus",o.getOrderStatus());
        String address = addressDao.findByOrderId(o.getId());
        order.put("address",address);
        return order;
    }

    @Override
    public List<Map> findBydate(Map map) {
        List<Order> orders= orderDao.findBydate(map);
        List orderList = new ArrayList();
        for (Order order : orders) {
            Map orderMap = new HashMap();
            Integer memberId = order.getMemberId();
            String memberName = memberDao.findNameById(memberId);
            orderMap.put("memberName",memberName);
            System.out.println(memberName);
            orderMap.put("memberId",memberId);
            Integer setmealId = order.getSetmealId();
            String setmealName = checkSetmealDao.findNameById(setmealId);
            orderMap.put("setmealId",setmealId);
            orderMap.put("setmealName",setmealName);
            orderList.add(orderMap);
        }
        return orderList;
    }

    @Override
    public Map<String,Object> findByDate(String beginTime, String afterTime) {
        List<Order> order = orderDao.findByDate(beginTime, afterTime);
        List<Integer> statusok = new ArrayList<>();
        List<Integer> statusno = new ArrayList<>();
        List<String> dates = new ArrayList<>();
        for (Order order1 : order) {
            Date orderDate = order1.getOrderDate();
            try {
                dates.add(DateUtils.parseDate2String(orderDate));
                List<Map> numberByDate = orderDao.getNumberByDate(DateUtils.parseDate2String(orderDate));
                if (numberByDate.size()>1) {
                    for (Map map : numberByDate) {
                        if (map.get("status").equals("已完成")){
                            long number1 = (long) map.get("number");
                            Integer number = new Long(number1).intValue();
                            statusok.add(number);
                        }else {
                            long number1 = (long) map.get("number");
                            Integer number = new Long(number1).intValue();
                            statusno.add(number);
                        }
                    }
                }else if (numberByDate.size()==1){
                    Map map = numberByDate.get(0);
                    if (map.get("status").equals("已完成")){
                        long number1 = (long) map.get("number");
                        Integer number = new Long(number1).intValue();
                        statusok.add(number);
                        statusno.add(0);
                    }else {
                        long number1 = (long) map.get("number");
                        Integer number = new Long(number1).intValue();
                        statusno.add(number);
                        statusok.add(0);
                    }
                }else {
                    statusok.add(0);
                    statusno.add(0);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        Map<String,Object> map = new HashMap();
        map.put("allDate",dates);
        map.put("perOrder",statusno);
        map.put("perCome",statusok);
        return map;
    }

    @Override
    public List<Map<String, Object>> getSetmealCount() {
        return orderDao.getSetmealCount();

    }


    @Override
    public void change(Integer id) {
        String status = orderDao.findStatus(id);
        if (status.equals("未到诊")){
            orderDao.change(id);
        }else {
            orderDao.change1(id);
        }

    }

    @Override
    public void edit(OderIofo oderIofo) {
        String name = oderIofo.getName();

        Integer id=memberDao.findByName(name);
        Map<String,Object> map=new HashMap<>();
        map.put("id",id);
        map.put("OrderDate",oderIofo.getOrderDate());
        map.put("OrderStatus",oderIofo.getOrderStatus());
        map.put("OrderType",oderIofo.getOrderType());
        orderDao.edit(map);
    }

    @Override
    public List<Integer> find(Integer id) {
        return orderDao.find(id);
    }


    //体检预约
    @Override
    public Result order(Map map,Integer id) throws Exception {

        //检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }


        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //预约已满，不能预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //检查当前用户是否为会员，根据手机号判断
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        //防止重复预约
        if(member != null){
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String) map.get("setmealId"));
            Order order = new Order(memberId,date,null,null,setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //已经完成了预约，不能重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }



        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        if(member == null){
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //保存预约信息到预约表

        Order order = new Order(member.getId(), date, (String)map.get("orderType"),

                Order.ORDERSTATUS_NO,

                Integer.parseInt((String) map.get("setmealId")));

                orderDao.add(order);

        addressDao.addOrderAndAddress(order.getId(),id);

        return new Result(true, MessageConstant.ORDER_SUCCESS,order.getId());
    }


    @Override
    public Map findById(int id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        String remark = addressDao.findRemark(id);
        map.put("remark",remark);
        return map;
    }


}
